﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Ragim.Selfpub.CrmSolution.Plugins.Tools;

namespace Ragim.Selfpub.CrmSolution.Plugins.Tools
{
    public class CrmSettings
    {
        public string CrmUrlWithPortAndOrgname { get; set; }
        public EntityReference CallcenterTeam { get; set; }
        public EntityReference SalesTeam { get; set; }
        public EntityReference AdminUser { get; set; }

        public CrmSettings(IOrganizationService crmService)
        {
            string step = "";
            try
            {
                step = "1";
                List<string> cols = new List<string>() { "new_crmurlwithportandorgname", "new_sales_team", "new_callcenter_team", "new_adminuser" };

                step = "2";
                QueryExpression query = new QueryExpression("new_settings")
                {
                    ColumnSet = new ColumnSet(cols.Select(x => x.ToLower()).ToArray()),
                    PageInfo = new PagingInfo() { Count = 1, PageNumber = 1 },
                    NoLock = true
                };

                step = "3";
                var qqq = crmService.RetrieveMultiple_Custom(query)[0];

                step = "4";
                CrmUrlWithPortAndOrgname = qqq.GetStringAttributeValue("new_crmurlwithportandorgname");
                SalesTeam = qqq.GetEntityReferenceAttributeValue("new_sales_team");
                CallcenterTeam = qqq.GetEntityReferenceAttributeValue("new_callcenter_team");
                AdminUser = qqq.GetEntityReferenceAttributeValue("new_adminuser");
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(OperationStatus.Failed,
                  string.Format("Error on [CrmSettings] [step = '{0}']: {1}", step, ex.ToString()));
            }
        }
    }
}
